package ai.assist.common.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class ThreadUtil {

    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-%d").build();

    private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(80, 100, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>()) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            if (r instanceof Thread) {
                if (t != null) {
                    //处理捕获的异常
                    log.error("线程：{}，出现异常！", ((Thread) r).getName(), t);
                }
            } else if (r instanceof FutureTask) {
                FutureTask futureTask = (FutureTask) r;
                try {
                    futureTask.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    //处理捕获的异常
                    log.error("线程，出现异常！", e);
                }
            }
        }
    };

    public static Executor getThreadPool() {
        return threadPool;
    }

    public static Executor getThreadPool(Integer threadNum) {
        return new ThreadPoolExecutor(threadNum, 50,
                0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    }

}
